const md5 = require('md5')
const jwt = require('jsonwebtoken')
const dayjs = require('dayjs')
const { loginDao, registerDao, getSupplierByName, getSupplierByCode, getSupplierByEmail, getSupplierByTelphone, updateSupplier } = require('../dao/webDao')
const { ValidationError } = require('../utils/errors')


exports.loginService = async function(info) {
    let data = await loginDao(info)
    console.log('================= data', data);
    let token = ''
    if (data) {
        // 添加token
        token = jwt.sign({
            _id: data._id,
            c_name: data.c_name,
            c_code: data.c_code,
            c_email: data.c_email
        }, md5(process.env.JWT_SECRET), { expiresIn: 60*60*24})
    }
    return { data, token }
}

exports.registerService = async function(info) {
    info.c_password = md5(info.c_password)
    let res = await getSupplierByName(info)
    if (res) {
        throw new ValidationError('企业名称重复')
    }
    res = await getSupplierByCode(info)
    if (res) {
        throw new ValidationError('统一社会信用代码重复')
    }
    res = await getSupplierByEmail(info)
    if (res) {
        throw new ValidationError('电子邮箱重复')
    }
    res = await getSupplierByTelphone(info)
    if (res) {
        throw new ValidationError('联系电话重复')
    }
    console.log('----------------------------- >>>');
    info.c_state = '99'
    info.c_time = dayjs(Date.now()).format('YYYY/MM/DD HH:mm:ss')
    return await registerDao(info)
}

exports.updateSupplierService = async function(info) {
    let data = await updateSupplier(info)
    console.log('------------------- update', data);
    return data
}

exports.getSupplierService = async function(info) {
    return await getSupplierByCode(info)
}
